<template>
  <!-- echarts 的容器 -->
  <div ref="divRef" :style="{ width: width, height: height }"></div>
</template>

<script setup>
import { onMounted, ref, watch, nextTick, onUnmounted } from 'vue'
import * as echarts from 'echarts'
// 监听 options 的变化
let hyChart = null
const divRef = ref(null)
const props = defineProps({
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '100%'
  },
  options: {
    type: Object,
    default: () => ({})
  }
})

watch(
  () => props.options,
  (newOptions) => {
    hyChart?.setOption(newOptions)
  },
  {
    deep: true
  }
)

onMounted(() => {
  setupEchart()
})

onUnmounted(() => {
  hyChart?.dispose()
  hyChart = null
})

async function setupEchart() {
  await nextTick()
  if (divRef.value) {
    hyChart = echarts.init(divRef.value, null, { renderer: 'svg' })
    hyChart?.setOption(props.options)
    window.addEventListener('resize', () => {
      hyChart?.resize()
    })
  }
}
</script>

<style scoped lang="scss"></style>
